import configs from "@/config/config.js"
import storage from "@/uni-sub-base/utils/storage.js"
import uniCopy from "@/uni-sub-base/plugins/uni-copy.js"
import store from "@/store/index.js"
//全局工具类
const utils = {
    //去重
    setReduce(arr, name) {
        var hash = {}
        return arr.reduce(function (item, next) {
            hash[next[name]] ? "" : (hash[next[name]] = true && item.push(next))
            return item
        }, [])
    },
    //数组排序
    sortBykey(ary, key) {
        return ary.sort(function (a, b) {
            let x = a[key]
            let y = b[key]
            return x < y ? -1 : x > y ? 1 : 0
        })
    },
    getCurrPage() {
        try {
            let pages = getCurrentPages()
            if (pages.length) {
                return pages[pages.length - 1]
            }
        } catch (e) {}
        return undefined
    },
    getNavigationBarTitle() {
        let page = utils.getCurrPage()
        if (page) {
            let view = page.$holder
            if (view) {
                // h5
                return view.navigationBar.titleText
            } else {
                // app-plus
                try {
                    view = page.$getAppWebview()
                    if (view) {
                        const style = view.getStyle()
                        if (style && style.titleNView) {
                            return style.titleNView.titleText
                        }
                    }
                } catch (e) {
                    if (process.env.NODE_ENV !== "production") {
                        return page.route
                    }
                }
            }
        }
        return ""
    },
    getUrlTarget() {
        let page = utils.getCurrPage()
        if (page) {
            return page.route
        }
        return ""
    },

    /**
     * 倒计时
     * @params(string)  endtime  结束时间
     * @params(func)	callback	回调
     */
    getRemainTime(endtime, callback) {
        showtime()

        function addZero(i) {
            if (i < 10) {
                i = "0" + i
            }
            return i
        }

        function showtime() {
            var _nowtime = new Date()
            var _endtime = new Date(endtime.replace(/\-/g, "/"))
            var lefttime = parseInt((_endtime.getTime() - _nowtime.getTime()) / 1000)
            var d = parseInt(lefttime / (24 * 60 * 60))
            var h = parseInt((lefttime / (60 * 60)) % 24)
            var m = parseInt((lefttime / 60) % 60)
            var s = parseInt(lefttime % 60)
            h = addZero(h)
            m = addZero(m)
            s = addZero(s)
            if (lefttime <= 0) {
                callback(d, h, m, s)
                return
            }
            setTimeout(showtime, 1000)
            callback(d, h, m, s)
        }
    },

    /**
     * 修改时间格式
     * @params(date)  date  待处理日期
     * @params(string)	format	格式
     */
    dateFomat(date, format) {
        const opt = {
            "y+": date.getFullYear().toString(), // 年
            "m+": (date.getMonth() + 1).toString(), // 月
            "d+": date.getDate().toString(), // 日
            "H+": date.getHours().toString(), // 时
            "M+": date.getMinutes().toString(), // 分
            "S+": date.getSeconds().toString(), // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
        }

        for (var k in opt) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(
                    RegExp.$1,
                    RegExp.$1.length == 1 ? opt[k] : ("00" + opt[k]).substr(("" + opt[k]).length),
                )
            }
        }
        return format
    },

    // 选择月份起始
    chooseMonth(date) {
        const monthStart = new Date(date.setDate(1))
        const y = utils.dateFomat(date, "yyyy")
        const m = utils.dateFomat(date, "m")
        const d = new Date(y, m, 0).getDate()
        const monthEnd = new Date(y, m - 1, d)
        const startDate = utils.dateFomat(monthStart, "yyyy-mm-dd")
        const endDate = utils.dateFomat(monthEnd, "yyyy-mm-dd")
        return {
            startDate,
            endDate,
        }
    },

    /**
     * 判断文档离是否含有某个文件
     */
    isInclude(name) {
        var js = /js$/i.test(name)
        var es = document.getElementsByTagName(js ? "script" : "link")
        for (var i = 0; i < es.length; i++) {
            if (es[i][js ? "src" : "href"].indexOf(name) != -1) {
                return true
            }
        }
        return false
    },
    /**
     * 距离换算（小于100m显示"<100m"，小于1000m显示m，大于1000m显示km）
     * @param {*} distance 距离
     */
    distanceChange(distance) {
        let _distance = "距离未知"
        if (distance === 999999) {
            _distance = "距离未知"
        } else if (distance > 1000) {
            _distance = ">1000km"
        } else if (distance > 0) {
            _distance = distance.toFixed(1) + "km"
        }
        return _distance
    },
    //复制内容到黏贴板
    copyFn(text) {
        uniCopy({
            content: text,
            success: (res) => {
                uni.showToast({
                    title: res,
                    icon: "none",
                })
            },
            error: (e) => {
				console.log(e)
                uni.showToast({
                    title: e,
                    icon: "none",
                    duration: 3000,
                })
            },
        })
    },
    /**
     * 获取评分name
     * @param {*} star 评分
     */
    getStarName(star) {
        switch (star) {
            case 1:
                return "非常差"
            case 2:
                return "差"
            case 3:
                return "一般"
            case 4:
                return "好"
            case 5:
                return "非常好"
        }
    },
    gotoLoginUni() {
		if(store.state.skipone==1){
			store.commit('SKIP_ADD')
			console.log(store.state.skipone)
			console.log('skipone')
			store.commit('CLEAR_AUTH')
			storage.removeCache("token")
			storage.removeCache("userInfo")
			storage.removeCache("productDisplay")
			storage.removeCache("webInfo")
			storage.removeCache("selectShop")
			storage.removeCache("themeColor")
			uni.reLaunch({
			    url: "/pages/login/loading",
			})
			setTimeout((e)=>{
				store.commit('SKIP_RESET')
			},5000)
		}
		
    },
    gotoLogin() {
        let webInfo = storage.getCache("webInfo")
        if (!webInfo || webInfo.LoginState == 1) {
            // 自动登录不要跳h5登录页
            return
        }
        // 获取当前路由
        const routes = getCurrentPages()
        const fullPath = routes[routes.length - 1].$page.fullPath
        const back_url = "/uniPage/#" + fullPath //登录返回地址
        const domain = webInfo.MobileDomain || configs.baseSiteUrl
        let _page = domain + "/m/user/loginnav"

        // 获取邀请人链接
        const _urlList = fullPath.split("?")
        let query = ""
        if (_urlList && _urlList.length > 1) {
            query = _urlList[_urlList.length - 1]
        }
        if (query) {
            const arr = query.split("&")
            if (arr.length > 0) {
                arr.forEach((tem) => {
                    if (tem.indexOf("invit_user") !== -1) {
                        _page += "?" + tem
                    }
                })
            }
        }
        if (_page.includes("?")) {
            _page += "&back_url=" + encodeURIComponent(back_url)
        } else {
            _page += "?back_url=" + encodeURIComponent(back_url)
        }
        const uniPath = "/pages/web/view?url=" + encodeURIComponent(_page)
        uni.navigateTo({
            url: uniPath,
        })
    },
}

module.exports = {
    setReduce: utils.setReduce,
    sortBykey: utils.sortBykey,
    getNavigationBarTitle: utils.getNavigationBarTitle,
    getUrlTarget: utils.getUrlTarget,
    getRemainTime: utils.getRemainTime,
    dateFomat: utils.dateFomat,
    chooseMonth: utils.chooseMonth,
    isInclude: utils.isInclude,
    distanceChange: utils.distanceChange,
    getStarName: utils.getStarName,
    gotoLogin: utils.gotoLogin,
    gotoLoginUni: utils.gotoLoginUni,
    copyFn: utils.copyFn,
}
